package com.epc.easypurchase.activity

import android.Manifest
import android.app.Activity.RESULT_OK
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.view.View
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.epc.easypurchase.bean.JsonBean
import com.epc.easypurchase.util.GetJsonDataUtil
import com.google.gson.Gson
import com.jiazhuo.blockgamesquare.util.toast
import com.woochen.baselibrary.base.mvp.BaseMvpActivity
import com.woochen.baselibrary.util.StatusBarUtil
import kotlinx.android.synthetic.main.activity_complete_information.*
import org.json.JSONArray
import java.util.ArrayList
import com.zhihu.matisse.engine.impl.GlideEngine
import android.content.pm.ActivityInfo
import android.net.Uri
import android.text.TextUtils
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.epc.easypurchase.AppApplication.Companion.mContext
import com.epc.easypurchase.R
import com.epc.easypurchase.R.id.*
import com.epc.easypurchase.bean.UploadResponseBean
import com.epc.easypurchase.constant.SPUserConstants
import com.epc.easypurchase.mvp.contract.PurChaseContract
import com.epc.easypurchase.mvp.contract.SupplyContract
import com.epc.easypurchase.mvp.contract.UploadTokenContract
import com.epc.easypurchase.mvp.presenter.PurChasePresenter
import com.epc.easypurchase.mvp.presenter.SupplyPresenter
import com.epc.easypurchase.mvp.presenter.UploadTokenPresenter
import com.epc.easypurchase.util.SPUserUtil
import com.jiazhuo.blockgamesquare.constant.Constants
import com.jiazhuo.blockgamesquare.constant.Constants.toast
import com.qiniu.android.storage.Configuration
import com.qiniu.android.storage.UpCompletionHandler
import com.qiniu.android.storage.UploadManager
import com.tbruyelle.rxpermissions2.RxPermissions
import com.woochen.baselibrary.mvp.InjectPresenter
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.internal.entity.CaptureStrategy


class CompleteInformationActivity : BaseMvpActivity(), View.OnClickListener, UploadTokenContract.IUploadTokeneView, SupplyContract.ISupplyView, PurChaseContract.IPurChaseView {


    private var options1Items = ArrayList<JsonBean>()
    private val options2Items = ArrayList<ArrayList<String>>()
    private val options3Items = ArrayList<ArrayList<ArrayList<String>>>()
    private var isLoaded = false
    private var request_code_choose: Int = 0

    @InjectPresenter
    lateinit var mUploadTokenPresenter: UploadTokenPresenter

    /**
     * 七牛上传配置
     */
    private val config by lazy {
        Configuration.Builder()
                .chunkSize(512 * 1024)        // 分片上传时，每片的大小。 默认256K
                .putThreshhold(1024 * 1024)   // 启用分片上传阀值。默认512K
                .connectTimeout(10)           // 链接超时。默认10秒
                .useHttps(true)               // 是否使用https上传域名
                .responseTimeout(60)          // 服务器响应超时。默认60秒
                .build()
    }


    private val uploadManager by lazy {
        UploadManager(config)
    }

    /**
     * 七牛token
     */
    private var uploadToken = ""


    override fun setContentView(): Int = R.layout.activity_complete_information

    override fun initData() {
        StatusBarUtil.statusBarTintColor(this, R.color.colorBlue1)
        parseData()
        initUploadParam()
        initIntent()
        initListener()

    }

    private var userType: Int = 0 //用户类型

    private fun initIntent() {
        userType = intent.getIntExtra(USER_TYPE, 0)

    }

    companion object {

        private val USER_TYPE: String? = "user_type"

        fun start(context: Context, type: Int) {
            val intent = Intent(context, CompleteInformationActivity::class.java)
            intent.putExtra(USER_TYPE, type)
            context.startActivity(intent)
        }
    }


    private fun initListener() {
        tv_company_address.setOnClickListener(this)
        iv_open_account.setOnClickListener(this)
        iv_manage_pic.setOnClickListener(this)
        iv_grant.setOnClickListener(this)
        iv_positive_card.setOnClickListener(this)
        iv_opposite_card.setOnClickListener(this)
        tv_add_certify.setOnClickListener(this)
    }


    private fun showPickerView() {// 弹出选择器
        if (!isLoaded) {
            toast("Please waiting until the data is parsed")
            return
        }
        val pvOptions = OptionsPickerBuilder(this, OnOptionsSelectListener { options1, options2, options3, v ->
            //返回的分别是三个级别的选中位置
            provinceName = options1Items[options1].pickerViewText
            cityName = options2Items[options1][options2]
            areaName = options3Items[options1][options2][options3]
            tv_company_address.text = provinceName +" " + cityName +" "+ areaName
//            toast("$provinceName $cityName $areaName")
        })
                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build<Any>()
        pvOptions.setPicker(options1Items as List<Any>?, options2Items as List<MutableList<Any>>?, options3Items as List<MutableList<MutableList<Any>>>?)//三级选择器
        pvOptions.show()
    }


    override fun onClick(v: View?) {
        when (v) {
            tv_company_address -> showPickerView()
            iv_open_account -> pickPic(0)
            iv_manage_pic -> pickPic(1)
            iv_grant -> pickPic(2)
            iv_positive_card -> pickPic(3)
            iv_opposite_card -> pickPic(4)
            tv_add_certify -> pickPic(5)
            tv_confirm -> commitData()
        }
    }

    var provinceName: String = ""//省
    var cityName: String = ""//市
    var areaName: String = ""//区

    /*  var open_account_pic_url: String = ""//开户行证明照片
      var manage_pic_url: String = ""//营业执照照片
      var grant_pic_url: String = ""//带公章的授权书照片
      var positive_card_pic_url: String = ""//法人身份证正面照
      var opposite_card_pic_url: String = ""//法人身份证背面照

      val open_account_pic_key: String = ""//开户行证明照片
      val manage_pic_key: String = ""//营业执照照片
      val grant_pic_key: String = ""//带公章的授权书照片
      val positive_card_pic_key: String = ""//法人身份证正面照
      val opposite_card_pic_key: String = ""//法人身份证背面照*/

    val picNames = arrayOfNulls<String>(6)
    val picViews = arrayOfNulls<ImageView>(6)
    val picUrls = arrayOfNulls<String>(6)
    val picKeys = arrayOfNulls<String>(6)
    private fun initUploadParam() {
        picNames[0] = "open_account_pic"//开户行证明照片名字
        picNames[1] = "manage_pic"//营业执照照片名字
        picNames[2] = "grant_pic"//带公章的授权书照片名字
        picNames[3] = "positive_card_pic"//法人身份证正面照名字
        picNames[4] = "opposite_card_pic"//法人身份证背面照名字
        picNames[5] = "certify_pic"//法人身份证背面照名字
        picViews[0] = iv_open_account
        picViews[1] = iv_manage_pic
        picViews[2] = iv_grant
        picViews[3] = iv_positive_card
        picViews[4] = iv_opposite_card
    }

    @InjectPresenter
    lateinit var mSupplyPresenter: SupplyPresenter

    @InjectPresenter
    lateinit var mPurChasePresenter: PurChasePresenter

    /**
     * 提交资料
     */
    private fun commitData() {
        val companyName = et_name.text.toString().trim()//公司名称
        val companyCode = et_company_code.text.toString().trim()//统一信用代码
        val bankName = ev_bank_name.text.toString().trim()//开户银行
        val bankAccount = et_bank_account.text.toString().trim()//开户银行账号
        val companAddress = tv_company_address.text.toString().trim()//省市区
        val companAddressDetail = tv_company_address_detail.text.toString().trim()//公司地址详情
        val certifyName = et_certify_name.text.toString().trim()//资质证书
        val cardNumber = et_card_number.text.toString().trim()//法人身份证号码
        if (
//                TextUtils.isEmpty(open_account_pic_url)||TextUtils.isEmpty(manage_pic_url)
//                ||TextUtils.isEmpty(grant_pic_url)||TextUtils.isEmpty(positive_card_pic_url)
//                ||TextUtils.isEmpty(opposite_card_pic_url) ||
        TextUtils.isEmpty(companyName)
                || TextUtils.isEmpty(companyCode) || TextUtils.isEmpty(bankName)
                || TextUtils.isEmpty(bankAccount) || TextUtils.isEmpty(companAddress)
                || TextUtils.isEmpty(companAddressDetail) || TextUtils.isEmpty(certifyName)
                || TextUtils.isEmpty(cardNumber)) {
            toast("信息不完整！")
            return
        }
        val uid = SPUserUtil.getString(SPUserConstants.USER_ID)
        when (userType) {
            Constants.TYPE_SUPPLY -> {
                mSupplyPresenter.completeSupply(picKeys[0]!!, areaName, picKeys[1]!!, picKeys[2]!!,
                        cityName, companAddressDetail, companyName, picKeys[4]!!, picKeys[3]!!, cardNumber,
                        provinceName, bankAccount, bankName, picKeys[5]!!, certifyName, companyCode, uid!!)
            }
            Constants.TYPE_PURCHASE -> {
                mPurChasePresenter.completePurChase(picKeys[0]!!, areaName, picKeys[5]!!, certifyName, picKeys[1]!!, picKeys[2]!!,
                        cityName, companAddressDetail, companyName, picKeys[4]!!, picKeys[3]!!, cardNumber, provinceName, bankAccount, bankName, companyCode, uid!!)
            }
        }
    }

    override fun completeSupplySucess() {
        finish()
    }

    override fun completePurChaseSucess() {
        finish()
    }

    val rxPermissions by lazy {
        RxPermissions(this)
    }

    /**
     * 选择图片
     */
    private fun pickPic(request_code: Int) {
        request_code_choose = request_code
        rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe() { grant ->
            if (grant) {
                Matisse.from(this)
                        .choose(MimeType.ofAll(), false)
                        .countable(true)
                        .capture(true)
                        .captureStrategy(CaptureStrategy(true, "com.epc.easypurchase.fileprovider"))
                        .maxSelectable(1)
                        .gridExpectedSize(resources.getDimensionPixelSize(R.dimen.grid_expected_size))
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                        .thumbnailScale(0.85f)
                        .imageEngine(GlideEngine())
                        .forResult(request_code)
            } else {
                toast("请打开摄像头权限！")
            }
        }

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == request_code_choose && resultCode == RESULT_OK) {
            showLoading(true)
            picUrls[request_code_choose] = Matisse.obtainPathResult(data)[0]
            mUploadTokenPresenter.getToken(picNames[request_code_choose]!!)
        }
    }

    override fun getTokenSucess(result: UploadResponseBean) {
        uploadToken = result.upToken
        val savingFileKey = result.savingFileKey
        if (savingFileKey.contains(picNames[request_code_choose]!!)) {
            uploadPic(picUrls[request_code_choose]!!, savingFileKey)
        }

    }


    /**
     * 图片上传到七牛
     */
    fun uploadPic(data: String, keyName: String) {
        uploadManager.put(data, keyName, uploadToken,
                UpCompletionHandler { key, info, res ->
                    //res包含hash、key等信息，具体字段取决于上传策略的设置
                    if (info.isOK) {
                        println("上传成功！")
                        picKeys[request_code_choose]
                        Glide.with(mContext).load(picUrls[request_code_choose]).into(picViews[request_code_choose])
                    } else {
                        toast("上传失败！")
                    }
                    showContent()
                }, null)
    }


    /**
     * 解析json数据
     */
    private fun parseData() {
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        val JsonData = GetJsonDataUtil().getJson(this, "province.json")//获取assets目录下的json文件数据
        val jsonBean = parseData(JsonData)//用Gson 转成实体
        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean
        for (i in jsonBean.indices) {//遍历省份
            val CityList = ArrayList<String>()//该省的城市列表（第二级）
            val Province_AreaList = ArrayList<ArrayList<String>>()//该省的所有地区列表（第三极）

            for (c in 0 until jsonBean[i].cityList.size) {//遍历该省份的所有城市
                val CityName = jsonBean[i].cityList[c].name
                CityList.add(CityName)//添加城市
                val City_AreaList = ArrayList<String>()//该城市的所有地区列表
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean[i].cityList[c].area == null || jsonBean[i].cityList[c].area.size === 0) {
                    City_AreaList.add("")
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea())
                }
                Province_AreaList.add(City_AreaList)//添加该省所有地区数据
            }
            options2Items.add(CityList)
            options3Items.add(Province_AreaList)
        }
    }


    fun parseData(result: String): ArrayList<JsonBean> {//Gson 解析
        val detail = ArrayList<JsonBean>()
        try {
            val data = JSONArray(result)
            val gson = Gson()
            for (i in 0 until data.length()) {
                val entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean::class.java)
                detail.add(entity)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        isLoaded = true
        return detail
    }

}
